<template>
	<view class="ball-team-reg-page">
		<view style="padding: 0 10px;margin-top: 10px;">
			<view class="form-sty">
				<text class="input-title ">球队Logo</text>
				<img class="img-sty" :src="logo[0].url" alt="" v-if="btnFla">
				<uni-file-picker v-else class="img-sty" :auto-upload="false" limit="1" mode="grid" :disablePreview="false" 
					v-model="logo" file-mediatype="image" :sizeType="sizeType" ref="logo" @fail="imgFail"
					@progress="imgProgress"   @delete="(e) => {delImg(e, 'logo')}"
					@select="(e)=>{imgSelect(e,'logo')}" @success="(e)=> {imgSuccess(e,'logo')}">
				</uni-file-picker>
			</view>
			<view class="form-sty">
				<text class="input-title bi-shu-sty">球队名称</text>
				<input class="input-sty" type="text" :disabled="btnFla" :maxlength="5" v-model.trim="formData.teamName" placeholder="球队名称">
			</view>
			<view class="form-sty" style="margin-top: 10px;">
				<text class="input-title bi-shu-sty">企事业单位主体</text>
				<text style="position: absolute;right: 50px;">营业执照等</text>
				<img class="img-sty" :src="companyImg[0].url" alt="" v-if="btnFla">
				<uni-file-picker v-else class="img-sty" :auto-upload="false" limit="1" mode="grid"
					:disablePreview="false" file-mediatype="image" :sizeType="sizeType" @fail="imgFail"
					@progress="imgProgress" ref="companyImg" v-model="companyImg" @delete="(e) => {delImg(e, 'companyImg')}"
					@select="(e)=>{imgSelect(e,'companyImg')}" @success="(e)=> {imgSuccess(e,'companyImg')}">
				</uni-file-picker>
			</view>
			<view class="form-sty">
				<text class="input-title">企事业注册地址</text>
				<input class="input-sty" type="text" :disabled="btnFla" :maxlength="50" v-model.trim="formData.trainingAddress"
					placeholder="企事业注册地址">
			</view>
			<view class="form-sty">
				<text class="input-title bi-shu-sty">管理员</text>
				<input class="input-sty" type="text" :disabled="btnFla" :maxlength="4" v-model.trim="formData.instructorF"
					placeholder="管理员姓名">
			</view>
			<view class="form-sty">
				<text class="input-title bi-shu-sty">管理员手机号</text>
				<input class="input-sty" type="text" :disabled="btnFla" :maxlength="11" v-model.trim="formData.instructorFP"
					placeholder="手机号" @blur="cheackPhone">
			</view>
			<view class="form-sty">
				<text class="input-title">领队</text>
				<input class="input-sty" type="text" :disabled="btnFla" :maxlength="4" v-model.trim="formData.responsibleName"
					placeholder="领队姓名">
			</view>
			<view class="form-sty">
				<text class="input-title">领队手机号</text>
				<input class="input-sty" type="text" :disabled="btnFla" :maxlength="11" v-model.trim="formData.responsiblePhone"
					placeholder="手机号" @blur="cheackPhone">
			</view>
			<view class="form-sty">
				<text class="input-title">教练</text>
				<input class="input-sty" type="text" :disabled="btnFla" :maxlength="4" v-model.trim="formData.instructorZ"
					placeholder="教练姓名">
			</view>
			<!-- 管理员与管理员电话 -->
			<view class="form-text-area">
				<text class="input-title">球队简介</text>
				<textarea class="text-area-sty" style="width: 100%;" :disabled="btnFla" :maxlength="100"
					v-model="formData.ballTeamIntroduce" placeholder="请输入" />
			</view>
			<view class="form-sty" style="margin-top: 10px;">
				<text class="input-title">球队合影</text>
				<img class="img-sty" :src="ballTeamPhoto[0].url" alt="" v-if="btnFla">
				<uni-file-picker v-else class="img-sty" :auto-upload="false" limit="1" mode="grid"
					:disablePreview="false" file-mediatype="image" :sizeType="sizeType" @fail="imgFail"
					@progress="imgProgress" ref="ballTeamPhoto" v-model="ballTeamPhoto" @delete="(e) => {delImg(e, 'ballTeamPhoto')}"
					@select="(e)=>{imgSelect(e,'ballTeamPhoto')}" @success="(e)=> {imgSuccess(e,'ballTeamPhoto')}">
				</uni-file-picker>
			</view>
			<!-- <view style="font-size: 28rpx;color:red;">球队大合照类型的宣传图</view> -->
			<view v-if="ballTeamId">
				<view>+球员注册</view>
				<view style="padding: 0 10px;">
					<view class="ball-play-info">
						<view>球员信息</view>
						<view style="text-align: right;">球员人数：{{playersList.length}}/15</view>
					</view>
					<view class="play-table-area" style="padding: 12px 0;">
						<view v-for="(item,index) in playTableTitle" :key="index">{{item.title}}</view>
					</view>
					<view class="play-table-area" v-for="play in playersList" :key="play._id">
						<view>
							<img style="width: 45px;height: 45px;vertical-align: middle;" :src="play.imgUrl" alt="">
							<view style="display: inline-block;margin-left: 10rpx;">{{play.userNm}}</view>
						</view>
						<view>{{play.height}}</view>
						<view>{{play.weight}}</view>
						<view>{{play.jerseyNum}}</view>
						<view><text v-if="userInfo.userType == 2" class="cz-btn" @click="removePlayer(play)">x</text>
						</view>
					</view>
				</view>
			</view>
			<view style="width: 100%;margin-top: 50px;padding-bottom: 50px;">
				<view class="btn-area" v-if="ballTeamId">
					<button data-name="shareBtn" open-type="share" class="share">球员注册分享</button>
				</view>
				<view class="btn-area" @click="restBtn" v-if="!ballTeamId && !btnFla">
					<view class="btn-sty">重置</view>
				</view>
				<view class="btn-area" @click="confirmBtn" v-if="!btnFla">
					<button class="btn-sty share" :disabled="btnFla"
						style="background: #fc993b;color: #fff;width: 150px;height: 38px;border-radius: 20px;">确认</button>
					<!-- <view class="btn-sty" style="background: #fc993b;color:#fff;" >确认</view> -->
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getImageList,
		cheackUser,
		verifyForm,
		checkFontRule
	} from '@/utils/baseFn.js';
	const db = uniCloud.database();
	const dbCmd = db.command;
	export default {
		data() {
			return {
				formData: {
					logo: '',
					teamName: '',
					trainingAddress: '',
					responsibleName: '',
					responsiblePhone: '',
					instructorZ: '',
					instructorF: '',
					instructorFP: '',
					companyImg: '',
					ballTeamPhoto: '',
					ballTeamIntroduce: ''
				},
				userInfo: {},
				logo: [],
				companyImg: [],
				ballTeamPhoto: [],
				sizeType: ['original', 'compressed'],
				playTableTitle: [{
						title: '球员'
					},
					{
						title: '身高cm'
					},
					{
						title: '体重kg'
					},
					{
						title: '球衣号'
					},
					{
						title: '操作'
					}
				],
				ballTeamId: null,
				typ: null,
				btnFla: false
			}
		},
		onLoad(op) {
			const _this = this
			if (op.id) {
				this.getBallTeamInfo(op.id)
			}
			this.typ = op.fla
			uni.setNavigationBarTitle({
				title: `${op.fla == 0?'公开组':'职工组'}球队注册`
			})
			uni.getStorage({
				key: 'userInfo',
				success: function(res) {
					console.log(res.data)
					if (res.data) {
						_this.userInfo = res.data
					}
				}
			})
			// if (op && op.id) {
			// 	this.ballTeamId = op.id
			// 	this.getPlayersList(op.id)
			// }
		},
		created() {},
		mounted() {},
		methods: {
			getBallTeamInfo(id) {
				const _this = this
				db.collection('team-MGMT').doc(id).field(
					"teamName,trainingAddress,responsibleName,responsiblePhone,instructorZ,instructorF,instructorFP,logo,deleted_at,state,type,ballTeamIntroduce,ballTeamPhoto,companyImg,opinion,createdUserId"
				).get().then((res) => {_this
					const data = res.result.data[0]
					if (data) {
						if (data.state == 1) { // 通过后不得修改只能协会管理员修改
							this.btnFla = true
						}
						this.opinionList = data.opinion ? JSON.parse(data.opinion) : []
						data.opinion = ''
						this.formData = data
						if (this.formData.logo) {
							this['logo'] = getImageList(this.formData.logo, this
								.$baseImgUrl)
						}
						if (this.formData.companyImg) {
							this['companyImg'] = getImageList(this.formData.companyImg, this
								.$baseImgUrl)
						}
						if (this.formData.ballTeamPhoto) {
							this['ballTeamPhoto'] = getImageList(this.formData.ballTeamPhoto,
								this.$baseImgUrl)
						}
						if (data.state == 2 && this.opinionList && this.opinionList.length > 0) {
							uni.showModal({
								content: `驳回建议：${_this.opinionList[0].op},请修改或联系管理员！`,
								showCancel: false
							})
						}
					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			getPlayersList(id) {
				const where = `"deleted_at"==null&&"ballTeamNm"=="${id}"`
				db.collection('user-MGMT').where(where).field(
					"userNm,jerseyNum,height,weight,portrait,ballTeamNm,deleted_at"
				).get().then((res) => {
					const data = res.result.data
					if (data) {
						this.playersList = data
					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {})
			},
			cheackPhone(e) {
				checkFontRule(e.detail.value, 0)
			},
			// 手动上传
			upload(f) {
				// 插件上传
				this.$refs[f].upload()
			},
			// 获取上传状态
			imgSelect(e, f, index = 0) {
				console.log('选择文件：', e)
				e.tempFiles.map(item => {
					if (`jpg,jpeg,png`.indexOf(item.extname) > -1) {
						if (item.size > 522183) {
							this.compress(item, index,f);
						} else {
							this.upload(f)
						}
					} else {
						this.upload(f)
					}
				})

			},
			// 删除附件
			delImg(e,f) {
				const _this = this
				uni.showModal({
					title: `删除图片？`,
					content: "删除后该图片将无法在页面展示，请谨慎删除！",
					success: async (res) => {
						if (!res.confirm) return false
						const annexFn = uniCloud.importObject('annex-del-fn')
						await annexFn.delFileFn([e.tempFile.fileID])
						_this.formData[f] = ''
					},
					fail: () => {
						uni.showToast({
							title: '删除失败',
							icon: 'none'
						})
					}
				})
			},
			// 获取上传进度
			imgProgress(e) {
				console.log('上传进度：', e)
			},
			// 上传成功
			imgSuccess(e,f) {
				const url = e.tempFilePaths[0].split('/')
				this.formData[f] = `${url[url.length - 1]},${e.tempFiles[0].name}`
				console.log('上传成功', e, this.formData[f])
			},
			// 上传失败
			imgFail(e) {
				console.log('上传失败：', e)
			},
			compress(r, index,f) { // 图片压缩
				var that = this;
				const num = r.size > 2251836 ? 3 : r.size < 1225836 ? 34 : 8
				console.log(r.size, '>522183原图大小', num, '压缩比例');
				if (r.size) {
					wx.compressImage({
						src: r.path,
						quality: num, // 0-100,越高却清晰
						success(res) {
							that.SizeImg(r, res, index, num,f);
						}
					})
				}
			},
			SizeImg(r, res, n, num,f) { // 查询图片大小
				let that = this;
				const arr = []
				wx.getFileInfo({ //查询压缩后的图片大小
					filePath: res.tempFilePath,
					success(ys) {
						let h = that.$refs[f].filesList[n].image.height * ((100 - num) / 100)
						let w = that.$refs[f].filesList[n].image.width * ((100 - num) / 100)
						console.log('压缩后的文件大小：' + ys.size);
						console.log('压缩后的临时路径：' + res.tempFilePath);
						that.$refs[f].filesList[n].path = res.tempFilePath
						that.$refs[f].filesList[n].size = ys.size
						that.$refs[f].filesList[n].url = res.tempFilePath
						that.$refs[f].filesList[n].image = {
							height: h,
							location: res.tempFilePath,
							width: w
						}
						that.$refs[f].filesList[n].width = w
						that.$refs[f].filesList[n].height = h
						that.$refs[f].filesList[n].location = res.tempFilePath
						that.upload(f)
					}
				})
			},
			removePlayer(item) {
				const _this = this
				const parm = {
					ballTeamNm: "",
					ballTeamType: null
				}
				if (item._id == this.userInfo._id) {

				}
				uni.showModal({
					content: '删除后无法恢复！确认删除？',
					success: function(res) {
						if (res.confirm) {
							db.collection('user-MGMT').doc(item._id).update().get().then((res) => {
								const data = res.result.data
								if (data) {
									this.playersList = data
								}
							}).catch((err) => {
								uni.showModal({
									content: err.message || '请求服务失败',
									showCancel: false
								})
							}).finally(() => {})
						}
					}
				})
			},
			restBtn() {
				this.formData = {
					logo: '',
					teamName: '',
					trainingAddress: '',
					responsibleName: '',
					responsiblePhone: '',
					instructorZ: ''
				}
			},
			confirmBtn() {
				console.log(this.imgList)
				const res = this.formData
				if (!verifyForm(res)) return
				if (!checkFontRule(res.instructorFP, 0)) return
				this.btnFla = true
				uni.showLoading({
					mask: true
				});
				const parm = {
					state: 0, // 0待审 1 通过 2退回
					deleted_at: null,
				}
				if (this.formData.createdUserId) {
					for (let k in this.formData) {
						if (k !== '_id') {
							parm[k] = this.formData[k]
						}
					}
					parm.state = 0
					if (this.opinionList && this.opinionList.length > 0) {
						parm.opinion = JSON.stringify(this.opinionList)
					}
					parm.updated_date = new Date().getTime()
					console.log(parm)
					return db.collection('team-MGMT').doc(this.formData._id).update(parm).then((res) => {
						uni.showToast({
							title: '修改成功'
						})
						this.btnFla = false
						setTimeout(() => uni.navigateBack({
							delta: 2
						}), 1228)
						uni.hideLoading();
					}).catch((err) => {
						this.btnFla = false
						uni.hideLoading();
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					})
				} else {
					db.collection('team-MGMT').where(`"deleted_at"==null&&"teamName"=="${res.teamName}"`).field(
						"responsibleName,responsiblePhone,instructorZ,teamName,state,opinion"
					).get().then((res) => {
						const data = res.result.data[0]
						const str = '请联系管理员或修改队名后提交 ！'
						let op
						if (data) {
							if (data.opinion) {
								op = JSON.parse(data.opinion)
							}
							if (data.state == 0) {
								uni.showModal({
									content: '球队重名，该球队审批中，' + str,
									showCancel: false
								})
							}
							if (data.state == 1) {
								uni.showModal({
									content: '球队重名，该球队已存在，' + str,
									showCancel: false
								})
							}
							if (data.state == 2) {
								uni.showModal({
									content: `球队重名，该球队审核被退回（原因：${op[op.length - 1].op}),` + str,
									showCancel: false
								})
								if (this.userInfo._id == data.createdUserId) {
									const annexFn = uniCloud.importObject('annex-del-fn')
									annexFn.delFileFn([this.imgList[0].fileID])
									this.formData = data
									const file = data.logo.split(',')
									this.imgList = [{
										fileID: `${this.$baseImgUrl}${file[0]}`,
										url: `${this.$baseImgUrl}${file[0]}`,
										name: file[1]
									}]
								}
							}
							this.btnFla = false
							uni.hideLoading();
							return
						}
						let value = {
							...this.formData,
							...parm
						}
						const y = new Date().getFullYear() + 1
						const ot = new Date(`${y}-01-01`).getTime()
						value.openTime = ot // 新增时将创建时间算作
						value.delNum = 0 // 新增时将删除次数赋值计入
						value.created_date = new Date().getTime()
						value.created_by = this.userInfo.userNm
						value.createdUserId = this.userInfo._id
						value.type = this.typ // 0 公开 1 职工
						return db.collection('team-MGMT').add(value).then((res) => {
							console.log(res)
							uni.showModal({
								content: '提交成功,待审批！',
								showCancel: false
							})
							this.btnFla = false
							setTimeout(() => uni.navigateBack({
								delta: 2
							}), 1228)
							uni.hideLoading();
						}).catch((err) => {
							this.btnFla = false
							uni.showModal({
								content: err.message || '请求服务失败',
								showCancel: false
							})
							uni.hideLoading()
						})
					}).catch((err) => {
						this.btnFla = false
						uni.hideLoading()
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					}).finally(() => {
						this.btnFla = false
						uni.hideLoading()
					})
				}
			}
		},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {

		},
		/**
		 * 用户点击右上角分享好友
		 */
		onShareAppMessage: function() {
			const obj = {
				id: this.ballTeamId,
				nm: this.formData.teamName,
				typ: this.formData.type,
				rpbNm: this.formData.responsibleName
			}
			return {
				path: `pages/sp-obj/register/playRegister?parm=${JSON.stringify(obj)}`,
				title: `${obj.nm}球员注册`,
			}
		},
		/**
		 * 用户点击右上角分享朋友圈
		 */
		onShareTimeline: function() {
			const obj = {
				id: this.ballTeamId,
				nm: this.formData.teamName,
				typ: this.formData.type,
				rpbNm: this.formData.responsibleName
			}
			return {
				path: 'pages/sp-obj/register/playRegister',
				query: `parm=${JSON.stringify(obj)}`,
				title: `${obj.nm}球员注册`
			}
		}
	}
</script>

<style>
	.ball-team-reg-page {
		height: 100vh;
	}

	.form-sty .uni-file-picker {
		display: inline-block;
		width: 50%;
	}

	.ball-play-info {
		padding: 12px 0;
		border-bottom: 1px solid #ccc;
	}

	.ball-play-info view {
		width: 50%;
		display: inline-block;
	}

	.input-title {
		width: 43%;
		display: inline-block;
		vertical-align: top;
	}

	.img-sty {
		width: 60%;
		height: 68px;
		display: inline-block;
	}

	.input-sty {
		width: 57%;
		display: inline-block;
		vertical-align: middle;
	}

	.form-sty {
		width: 100%;
		height: 70px;
		border-bottom: 1px solid #dcdfe6;
		line-height: 70px;
		padding: 0 5px;
	}

	.btn-area {
		width: 50%;
		text-align: center;
		display: inline-block;
		vertical-align: middle;
	}

	.btn-sty {
		width: 150px;
		height: 38px;
		color: #fc993b;
		background: #ffffff;
		border: 1px solid #fc993b;
		border-radius: 20px;
		line-height: 38px;
		margin: 0 auto;
	}

	.form-text-area {
		padding: 0 5px;
		margin-top: 20px;
		border-bottom: none;
	}

	.text-area-sty {
		width: 100%;
		height: 120px;
		margin-top: 10px;
		padding-bottom: 10px;
		border-bottom: 1px solid #ccc;
	}

	.bi-shu-sty::before {
		content: '*';
		position: relative;
		top: 0;
		left: 0;
		color: red;
	}
</style>
<style lang="scss">
</style>